import React, { Component } from 'react'
import { Form, Input, Tree} from 'antd';
import PropTypes from 'prop-types'
import menuList from '../../config/menuList'


export default class AuthForm extends Component {

  static propTypes = {
    role: PropTypes.object
  }

  state = {
    checkedKeys:this.props.role.menus
  }

  // 树形控件数据
  getTreeData = (menuList)=>{
    let newTreeData = []
    menuList.map((menu)=>{
      if(!menu.children){
        return newTreeData.push({title:menu.label,key:menu.key})
      }else{
        return newTreeData.push({title:menu.label,key:menu.key,children:this.getTreeData(menu.children)})
      }
    })
    return newTreeData
  }

  onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };

  // 更新选中
  onCheck = (checkedKeys, info) => {
    // console.log('onCheck', checkedKeys, info);
    this.setState ({checkedKeys})
  };

  // 给父组件更新后的选中项
  getMenus = () => this.state.checkedKeys

  UNSAFE_componentWillMount(){
    const data = this.getTreeData(menuList)
    this.treeData = [
      {
        title: '平台权限',
        key: 'all',
        children: data
      },
    ]
    // this.setState({checkKeys:this.props.role.menus}) 只会执行一次,所以不能放在这了
  }

  // 组件接受新props调用 在render之前: 解决次选中的都是和第一次打开的角色一样bug
  UNSAFE_componentWillReceiveProps(nextProps) {
    const menus = nextProps.role.menus
    this.setState ({
      checkedKeys: menus
    })
  }

  

  
  render () {

    const {role} = this.props
    const {checkedKeys} = this.state
    const {treeData} = this

    const formItemLayout = {
      labelCol: { span: 4 },
      wrapperCol: { span: 20 }
    }

    return (
      <Form
      // layout="vertical"
      name="form_in_modal"
      {...formItemLayout}
      // initialValues={}
    >

      <Form.Item  label='角色名称'>
        <Input  disabled value={role.name} />
      </Form.Item>
      <Form.Item>
        <Tree
          checkable
          checkedKeys={checkedKeys}
          defaultExpandAll={true}
          onSelect={this.onSelect}
          onCheck={this.onCheck}
          treeData={treeData}
        />
      </Form.Item>
    </Form>
    )
  }
  
}
